package service

import (
	"context"
	"temp/util"

	"github.com/redis/go-redis/v9"
	"gorm.io/gorm"

	"temp/model"
)

type DeptService struct {
	db    *gorm.DB
	cache *redis.Client
}

func (d *DeptService) Detail(ctx context.Context, id string) (*model.Department, error) {
	var dept model.Department
	return &dept, d.db.WithContext(ctx).Where("id = ?", id).First(&dept).Error
}
func (d *DeptService) Create(ctx context.Context, dept *model.Department) error {
	return d.db.WithContext(ctx).Create(dept).Error
}

func (d *DeptService) Update(ctx context.Context, dept *model.Department) error {
	return d.db.WithContext(ctx).Model(&model.Department{}).Where("id = ?", dept.ID).Updates(dept).Error
}

func (d *DeptService) DeleteById(ctx context.Context, id string) error {
	var dept model.Department
	dept.ID = util.StringToInt64Unsafe(id)
	return d.Delete(ctx, &dept)
}

func (d *DeptService) Delete(ctx context.Context, department *model.Department) error {
	return d.db.WithContext(ctx).Delete(department).Error
}

func (d *DeptService) List(ctx context.Context, dept *model.Department) ([]*model.Department, error) {
	var depts []*model.Department
	return depts, d.db.WithContext(ctx).Where(dept).Find(&depts).Error
}

// Tree 构建部门树形结构
func (d *DeptService) Tree(ctx context.Context, dept *model.Department) ([]*model.Tree[model.Department], error) {
	// 查询符合条件的所有部门
	var departments []*model.Department
	if err := d.db.WithContext(ctx).Where(dept).Find(&departments).Error; err != nil {
		return nil, err
	}

	// 构建部门树
	return buildDepartmentTree(departments, 0), nil
}

// buildDepartmentTree 构建部门树的辅助函数
func buildDepartmentTree(departments []*model.Department, parentID int64) []*model.Tree[model.Department] {
	var trees []*model.Tree[model.Department]

	// 查找指定parentID的直接子部门
	for _, dept := range departments {
		if dept.Parent == parentID {
			// 为当前部门创建树节点
			tree := model.NewTree(dept)

			// 递归查找并构建子树
			children := buildDepartmentTree(departments, dept.ID)
			for _, child := range children {
				tree.AddChild(child)
			}

			trees = append(trees, tree)
		}
	}

	return trees
}

func NewDeptService(db *gorm.DB, cache *redis.Client) *DeptService {
	return &DeptService{
		db:    db,
		cache: cache,
	}
}
